from datetime import datetime, timedelta, date
from loguru import logger
import requests


# 生成日期范围的函数
def generate_date_range(start_date: str, end_date: str):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    date_range = [start + timedelta(days=x) for x in range((end - start).days + 1)]
    return [date.strftime("%Y-%m-%d") for date in date_range]


# 根据输入天数生成日期的函数
def generate_dates_from_offset(base_date: str, offset: int):
    base = datetime.strptime(base_date, "%Y-%m-%d")
    dates = (
        [base + timedelta(days=x) for x in range(offset + 1)]
        if offset >= 0
        else [base - timedelta(days=x) for x in range(abs(offset) + 1)]
    )
    return [date.strftime("%Y-%m-%d") for date in dates]


# 把日期格式转成字符串
def timestamp_to_string(timestamp):
    date_time = datetime.fromtimestamp(timestamp)
    return date_time.strftime("%Y-%m-%d %H:%M:%S")


def get_current_and_previous_day_strings(timestamp):
    # 将时间戳转换为日期对象
    current_date = datetime.fromtimestamp(timestamp)
    # 获取当前日期的字符串格式
    current_date_string = current_date.strftime("%Y-%m-%d")
    # 减去一天
    previous_date = current_date - timedelta(days=1)
    # 获取前一天日期的字符串格式
    previous_date_string = previous_date.strftime("%Y-%m-%d")
    # 返回两个日期字符串
    return previous_date_string, current_date_string


def fetch_data(url):
    logger.info(f"fetching data from {url}")
    response = requests.get(url)
    return response.json()


def getdays(days=1):
    today = date.today()
    oneday = timedelta(days=days)
    yesterday = today - oneday
    return yesterday
